Repository navigation
Make local Gemma 4 load and parse correctly - #344
Merged
Merged
Conversation
Gemma 4 has been the on-device catalog's headline agent while quietly not working: the VLM factory could not map its weights, so it demoted to text on every load, its chat template did not render, and generation ran past the end of every answer. Three separate causes, fixed here. **Load.** The weight-mapping failure (`keyNotFound(…k_norm.weight, Gemma4RMSNormZeroShift)`) is fixed upstream — KV-shared layers must not declare `k_proj`/`v_proj`. No released mlx-swift-lm tag carries that commit, so the package moves from a tag to a revision that does, in `project.base.yml`, `Package.swift` and both resolved files (via `Scripts/update-package-resolved.sh`). The pin stops short of upstream's tip deliberately: the next commit retargets MLXFoundationModels at the Xcode 27 beta 5 SDK and does not compile on earlier 27.0 betas, and MLXHuggingFace pulls that module in through a default-on trait. The comment on the pin says when to move it forward. **Parse.** Gemma 4's real chat template lives in `chat_template.jinja` and uses constructs swift-jinja's parser rejects. `Gemma4ChatPrompt` renders that template by hand as the fallback — a genuine system turn (not merged into the first user turn), `<|turn>`/`<turn|>` delimiters, `assistant` renamed to `model`, and no speaker labels anywhere. The generic no-system-role repair is no longer applied to a template *parse* failure, which is what used to flatten the persona into the wearer's turn. **Stop.** `<turn|>` is the checkpoint's `eot_token` while its `eos_token` is the different `<eos>`, so it is declared through `LocalLLMService.modelConfiguration`. A Gemma 4 that loads through the VLM factory now takes one path for both text and photo turns, through the processor that owns its template and image tokenization. A photo turn's prefill is one unchunked forward pass, so how much prompt it can carry is a property of the device rather than the model: `LocalModelBudget.multimodalTurnPlan` keeps the wearer's configured prompt and history on a 12 GB phone and trims only where the memory actually runs out. The trimmed prompt is derived, not hardcoded — the configured prompt's identity line survives and the wearer's language is stated explicitly (`Config.compactVisionTurnPrompt`). The stale "vision doesn't load in this runtime" caveat comes off the two Gemma 4 catalog entries. Gemma chat-template and parsing fixes ported from #331 by @exadeci, re-composed onto current main. Taken: the hand-rendered template, the `<turn|>` stop token, the VLM-processor turn path, and the tests. Left: the unconditional prompt/history stripping (now RAM-tiered), the English literal photo prompt (now derived), the `sendLocal` tools/history change (redundant for Gemma, a regression for SmolVLM2), the direct swift-jinja dependency (nothing imports it; 2.4.2 already arrives through swift-transformers), and the photo-library/camera/recording changes, which another plan owns. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Local Gemma 4 has been the on-device catalog's headline agent while quietly not working. Three separate causes, all fixed here, so the keyless tier has a real assistant on any phone that runs MLX.
What
Load. The VLM weight-mapping failure (
keyNotFound(…k_norm.weight, Gemma4RMSNormZeroShift)) is fixed upstream — KV-shared layers must not declarek_proj/v_proj(mlx-swift-lm09deb8c). No released tag carries it (the newest, 3.31.4, predates it), so the package moves from a tag to a revision:project.base.yml,Package.swift,Package.resolvedandci_scripts/Package.resolved(regenerated withScripts/update-package-resolved.sh, not hand-edited).The pin is
d661402, one commit short of what #331 chose, deliberately. The next commit (1441444) retargets MLXFoundationModels at the Xcode 27 beta 5 SDK (27A5237l) and does not compile against earlier 27.0 betas —updateMetadatatakes[String: any Sendable & Codable & Equatable]there rather thanConvertibleToGeneratedContent. MLXHuggingFace pulls that module in through a default-on package trait, so the whole build fails on it. Verified: pinning1441444fails to build on this toolchain (27A5228h);d661402builds and still contains the Gemma fix. The comment on the pin says when to move it forward.Parse. Gemma 4's real chat template lives in
chat_template.jinjaand uses constructs swift-jinja's parser rejects.Gemma4ChatPromptrenders it by hand as the fallback — a genuine system turn (not merged into the first user turn),<|turn>/<turn|>delimiters,assistantrenamed tomodel, no speaker labels anywhere. A template parse failure no longer falls into the generic no-system-role repair, which is what used to flatten the persona into the wearer's turn.Stop.
<turn|>is the checkpoint'seot_tokenwhile itseos_tokenis the different<eos>, so it is declared throughLocalLLMService.modelConfiguration. Without it the model runs past the end of its answer into a hallucinated next turn.A Gemma 4 loaded through the VLM factory now takes one path for both text and photo turns, through the processor that owns its template and image tokenization; the hand-render is the fallback inside that path, not a parallel one.
Memory pressure, tiered
A photo turn's prefill is one unchunked forward pass, so how much prompt it can carry is a property of the device, not the model.
LocalModelBudget.multimodalTurnPlandecides: a 12 GB phone keeps its configured prompt and history; below that the turn is trimmed and the budget is scaled down. And the trimmed prompt is derived, not a hardcoded English literal —Config.compactVisionTurnPromptkeeps the configured prompt's identity line so a custom persona survives, and names the wearer's language explicitly so a non-English wearer isn't silently switched to English on every photo question.Credit
Gemma chat-template and parsing fixes ported from #331 by @exadeci, re-composed onto current main (the files moved since that branch, and the review conditions are applied rather than the code taken verbatim).
Taken: the hand-rendered chat template and its tests, the
<turn|>stop token, the VLM-processor turn path, the aspect-preserving image handling (no forced 896² pre-resize), the stale vision caveat coming off the two Gemma 4 catalog entries.Left, and why:
marketingRAMGB+LocalModelBudgetinstead, so a roomy phone doesn't pay for a tight one's problem.Config.swift.sendLocalimageData == nilchange — redundant for Gemma 4 (its turn path already empties both downstream) and a straight regression for SmolVLM2, which has no unchunked-prefill problem. Dropped.swift-jinjadependency — nothing importsJinja, and 2.4.2 (the version Gemma fix #331 pinned) already resolves transitively through swift-transformers 1.3.3. Adding it as a direct dependency would only be a second place to keep in sync.Localizable.xcstringschanges — a separate plan owns that audit.#331 is left open for the orchestrator to close out.
Testing
Everything on a dedicated iOS 27 simulator (created for this run, deleted after), Xcode 27 beta toolchain, isolated DerivedData,
SWIFT_EMIT_LOC_STRINGS=NO CODE_SIGNING_ALLOWED=NO.KeychainServiceTests,SecretMigrationTests, and theConfigTests/OpenClawAgentGateTestscases that read a gateway token from the keychain) — environment, not regression.Gemma4ChatPromptTestscover id matching, the rendered turn format (including that the system prompt stays its own turn and that no speaker labels appear), the extra stop token, template-parse-failure classification, both RAM tiers, and the derived photo prompt.LocalTokenShapeTests,LocalModelRoutingTests,LocalLocationFixTests,LocalModelBudgetTests. The pin is the part of this every user carries, including those who never touch Gemma; Qwen 2.5, SmolVLM2 and LFM2.5 routing, budget and token-shape contracts are green on the new revision.-configuration Release).Actual model loading is device work (P4) — no multi-GB download happens in any test.
🤖 Generated with Claude Code